<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="手机号码" prop="phonenumber" >
        <el-input
          v-model="queryParams.phonenumber"
          placeholder="请输入手机号码"
          clearable
          @keyup.enter="handleQuery"
          style="width: 220px"
        />
      </el-form-item>
      <el-form-item label="预约时间" prop="orderTime">
        <el-date-picker clearable
          v-model="queryParams.orderTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择预约时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="预约状态" prop="orderStatus">
        <el-select v-model="queryParams.orderStatus" placeholder="请选择预约状态" clearable>
          <el-option
              v-for="dict in lease_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="预约客户" prop="customerName" clearable>
        <el-select
            v-model="queryParams.customerName"
            placeholder="请选择客户"
            clearable
        >
          <el-option
              v-for="customer in customer"
              :key="customer.customerId"
              :label="customer.customerName"
              :value="customer.customerName"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="预约房间" prop="roomName" clearable>
        <el-select
            v-model="queryParams.roomName"
            placeholder="请选择房间"
            clearable
        >
          <el-option
              v-for="room in room"
              :key="room.roomId"
              :label="room.roomName"
              :value="room.roomName"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['lease:msg:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['lease:msg:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['lease:msg:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['lease:msg:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="msgList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="50" align="center" prop="customerId" />
      <el-table-column label="预约客户" align="center" prop="customerName" />
      <el-table-column label="预约房间" align="center" prop="roomName" />
      <el-table-column label="客户电话" align="center" prop="phonenumber" />
      <el-table-column
          label="预约时间"
          align="center"
          prop="orderTime"
          width="180"
          sortable
          :sort-method="sortByOrderTime">
        <template #default="scope">
          <span>{{ parseTime(scope.row.orderTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="预约状态" align="center" prop="orderStatus">
        <template #default="scope">
          <dict-tag :options="lease_status" :value="scope.row.orderStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['lease:msg:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['lease:msg:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改预约信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="msgRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="租客名称" prop="customerName">
          <el-select
              v-if="isAdd"
              v-model="form.customerName"
              placeholder="请选择前端用户"
              clearable
              @change=""
          >
            <el-option
                v-for="cust in customer"
                :key="cust.customerId"
                :label="cust.customerName"
                :value="cust.customerName"
            />
          </el-select>
          <el-input
              v-if="!isAdd"
              v-model="form.customerName"
              style="width: 220px"
              :readonly="true"
              placeholder="租客名称不可更改，您可以选择取消预约"
              @click="showMessage"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="公寓名称" prop="flatsName" clearable v-if="isAdd">
          <el-select
              v-if="isAdd"
              v-model="form.flatsName"
              placeholder="请选择公寓"
              clearable
              @change="updatePhoneNumberAndGetRoom"
          >
            <el-option
                v-for="flats in flatsList"
                :key="flats.flatsId"
                :label="flats.flatsName"
                :value="flats.flatsName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="公寓电话" prop="flatsPhoneNumber" v-if="isAdd"
        >
          <el-input
              v-model="form.flatsPhoneNumber"
              placeholder="公寓电话"
              readonly
              style="width: 220px"
          />
        </el-form-item>
        <el-form-item label="预约房间" prop="roomName" clearable>
          <el-tooltip v-if="!form.flatsName && isAdd" content="请先选择公寓" placement="top">
            <el-select
                v-model="form.roomName"
                placeholder="请选择房间"
                clearable
                :disabled="!form.flatsId"
            >
            </el-select>
          </el-tooltip>
          <el-select
          v-if="isAdd && form.flatsName"
          v-model="form.roomName"
          placeholder="请选择房间"
          clearable
          >
          <el-option
              v-for="room in roomBy"
              :key="room.roomName"
              :label="room.roomName"
              :value="room.roomName"
          />
          </el-select>
          <el-input
          v-if="!isAdd"
          v-model="form.roomName"
          style="width: 220px"
          :readonly="true"
          placeholder="房间名称不可更改，您可以选择取消预约"
          @click="showMessage"
          />
        </el-form-item>
        <el-form-item label="预约时间" prop="orderTime">
          <el-date-picker clearable
            v-model="form.orderTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择预约时间"
            :disabled-date="disabledDate">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="预约状态" prop="orderStatus">
          <el-radio-group v-model="form.orderStatus">
            <el-radio
              v-for="dict in lease_status"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Msg">
import {listMsg, getMsg, delMsg, addMsg, updateMsg, getMsgByKey} from "@/api/lease/msg";
import {ref} from "vue";
import {listCustomer, listNameCustomer} from "@/api/system/customer.js";
import {listRoom} from "@/api/apartment/room.js";
import {ElMessage} from "element-plus";
import {listFlats} from "@/api/apartment/flats.js";
import {getFlatsRoom} from "@/api/apartment/flatsroom.js";
import {listCity} from "@/api/apartment/location.js";
import {parseTime} from "../../../utils/ruoyi.js";

const {proxy} = getCurrentInstance();
const {lease_status} = proxy.useDict('lease_status');

const msgList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const customer = ref([]);
const room = ref([]);
const roomBy = ref([]);
const isAdd = ref(false);
const flatsList = ref([]); // 新增公寓列表
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    customerName: undefined,
    flatsName: undefined,
    flatsPhoneNumber: undefined,
    roomName: undefined,
    flatsId: undefined,
    phonenumber: undefined,
    orderTime: undefined,
    orderStatus: undefined
  },
  rules: {
    phonenumber: [{pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur"}],
    customerName: [{required: true, message: "租客名称不能为空", trigger: "blur"}],
    flatsName: [{required: true, message: "公寓名称不能为空", trigger: "blur"}],
    roomName: [{required: true, message: "房间名称不能为空", trigger: "blur"}],
    orderTime: [{required: true, message: "预约时间不能为空", trigger: "blur"}],
    orderStatus: [{required: true, message: "预约状态不能为空", trigger: "blur"}]
  }
});

const {queryParams, form, rules} = toRefs(data);

function sortByOrderTime(a, b) {
  return new Date(b.orderTime) - new Date(a.orderTime); // 按照时间升序排序
}

function getRowClass(row) {
  const currentTime = new Date().getTime(); // 获取当前时间
  const orderTime = new Date(row.orderTime.replace(" ", "T")).getTime(); // 将 orderTime 转换为时间戳

  // 如果 orderTime 小于当前时间，返回 'expired-row' 类名
  if(orderTime > currentTime){
    return '';
  }else{
    return 'expired-row';
  }
}

function getRoomsByFlatId(flatsId) {
  loading.value = true;
  getFlatsRoom(flatsId).then(response => {
    roomBy.value = response.rows; // 确保将房间数据赋值给 roomBy
    total.value = response.total;
    loading.value = false;
  }).catch(error => {
    loading.value = false; // 确保在出错时也停止加载
    console.error("获取房间数据失败:", error);
  });
}

/** 禁用过去的日期 */
function disabledDate(time) {
  return time.getTime() < Date.now(); // 禁用当前时间之前的日期
}

/** 租客列表 */
function getCustomerList() {
  loading.value = true;
  listCustomer(queryParams.value).then(response => {
    customer.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 房间列表 */
function getRoomList() {
  loading.value = true;
  listRoom(queryParams.value).then(response => {
    room.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 公寓列表 */
function getFlatsList() {
  // 这里需要调用 API 获取公寓列表
  // 假设有一个 API 方法 listFlats
  loading.value = true;
  listFlats().then(response => {
    flatsList.value = response.rows; // 假设返回的公寓数据在 rows 中
    loading.value = false;
  });
}


/** 查询预约信息列表 */
function getList() {
  loading.value = true;
  listMsg(queryParams.value).then(response => {
    msgList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    customerId: null,
    roomId: null,
    customerName: null,
    roomName: null,
    phonenumber: null,
    orderTime: null,
    orderStatus: null
  };
  proxy.resetForm("msgRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value1 = selection.map(item => item.customerId);
  ids.value2 = selection.map(item => item.roomId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  isAdd.value = true;
  open.value = true;
  title.value = "添加预约信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  isAdd.value = false;
  const _customerId = row.customerId || ids.value1
  const _roomId = row.roomId || ids.value2
  getMsgByKey(_customerId, _roomId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改预约信息";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["msgRef"].validate(valid => {
    if (valid) {
      if (isAdd.value = false) {
        updateMsg(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else if (isAdd.value = true) {
        addMsg(form.value).then(response => {
          if (response == 0) {
            ElMessage({
              message: '不可以重复新增相同的用户和房间，您可以修改已有数据',
              type: 'warning',  // 可以是 'success', 'warning', 'info', 或 'error'
              duration: 3000,   // 持续时间，单位为毫秒
              center: true      // 文字居中
            });
            open.value = false;
            getList();
          } else if (response == 1) {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            getList();
          }
        });
      }
    }
  });
}


/** 删除按钮操作 */
function handleDelete(row) {
  const _customerIds = row.customerId || ids.value;
  const _roomId = row.roomId || ids.value
  proxy.$modal.confirm('是否确认删除预约信息编号为"' + _customerIds + '"的数据项？').then(function () {
    return delMsg(_customerIds, _roomId);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('lease/msg/export', {
    ...queryParams.value
  }, `msg_${new Date().getTime()}.xlsx`)
}

function showMessage() {
  ElMessage({
    message: '不可更改，您可以选择取消预约',
    type: 'warning',  // 可以是 'success', 'warning', 'info', 或 'error'
    duration: 3000,   // 持续时间，单位为毫秒
    center: true      // 文字居中
  });
}

function updatePhoneNumberAndGetRoom() {
  const selectedFlat = flatsList.value.find(flat => flat.flatsName === form.value.flatsName);
  if (selectedFlat) {
    form.value.flatsPhoneNumber = selectedFlat.flatsPhoneNumber; // 更新电话
    getRoomsByFlatId(selectedFlat.flatsId);
  } else {
    form.value.flatsPhoneNumber = ''; // 清空电话
    roomBy.value = []; // 清空房间列表
  }
}


getList();
getCustomerList();
getRoomList();
getFlatsList();
</script>

